﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RouteTiming.Data;

namespace RouteTiming.DynamicModel
{
    public class DynamicContext
    {
        public RouteTimingContext Context{ get; private set; }

        public List<DynamicRoute> Routes { get; private set; }

        public DynamicContext() : this(new RouteTimingContext())
        {
            
        }

        public DynamicContext(RouteTimingContext context)
            : this(context, DateTime.Now, DateTime.Now + TimeSpan.FromDays(1))
        {
        }

        public DynamicContext(RouteTimingContext context, DateTime timeFrom, DateTime timeTill)
        {
            this.Context = context;

            this.Context.OnEventAdded += new Action<Event>(OnEventAdded);

            // initially loading routes
            this.Routes = new List<DynamicRoute>();
            this.LoadRoutes(timeFrom, timeTill);

            // processing existing events
            this.LoadExistingEvents(timeFrom, timeTill);
        }

        private void OnEventAdded(Event evt)
        {
            foreach (var route in this.Routes)
            {
                route.ProcessEvent(evt);
            }
        }

        private void LoadRoutes(DateTime timeFrom, DateTime timeTill)
        {
            var query = from r in this.Context.RouteSet select r;

            foreach(var route in query)
            {
                var dynamicRoute = new DynamicRoute(route, timeFrom, timeTill);

                this.Routes.Add(dynamicRoute);
            }
        }

        private void LoadExistingEvents(DateTime timeFrom, DateTime timeTill)
        {
            var query = from e in this.Context.EventSet select e;

            foreach(var evt in query)
            {
                this.OnEventAdded(evt);
            }
        }
    }
}
